package com.huangcy.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.huangcy.common.utils.HttpUtils;
import com.huangcy.common.utils.R;
import com.huangcy.common.vo.MemberRespVo;
import com.huangcy.gulimall.auth.Vo.SocialUserVo;
import com.huangcy.gulimall.auth.feign.MemberFeignService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @program: gulimall
 * @description: 处理社交登录
 * @author: huangcy
 * @create: 2022-08-29 13:23
 **/
@Controller
@Slf4j
public class OAuth2Controller {
    @Autowired
    MemberFeignService memberFeignService;


    @Value("${gitee.oauth.clientid}")
    private String clientId;
    @Value("${gitee.oauth.clientsecret}")
    private String clientSecret;
    @Value("${gitee.oauth.callback}")
    public String redirectUri;


    @GetMapping("/oauth2.0/gitee/success")
    public String gitee(@RequestParam("code") String code, HttpSession session, HttpServletResponse servletResponse) throws Exception {

        HashMap<String, String> header = new HashMap<>();
        HashMap<String, String> query = new HashMap<>();


//        https://gitee.com/api/v5/user?access_token=e4a563f8a7ce312f5d692e2b32ee1ff0
        HashMap<String, String> map = new HashMap<>();
        map.put("client_id", clientId);
        map.put("client_secret", clientSecret);
        map.put("redirect_uri", redirectUri);
        map.put("grant_type", "authorization_code");
        map.put("code", code);
        HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", header, query, map);

        if (response.getStatusLine().getStatusCode() == 200) {
            // 获取到了accessToken
            String json = EntityUtils.toString(response.getEntity());
            SocialUserVo socialUser = JSON.parseObject(json, SocialUserVo.class);
            // 知道当前是哪个社交用户
            //1)、 当前用户如果是第一次进网站，自动注册（为当前社交用户生成一个会员信息账号，以后这个社交账号就对应指定的会员）
            //登录或者注册
            R oauth2login = memberFeignService.oauth2login(socialUser);
            if (oauth2login.getCode() == 0) {
                MemberRespVo data = oauth2login.getData("data", new TypeReference<MemberRespVo>() {
                });
                log.info("登录成功：用户信息{}" + data);
                session.setAttribute("loginUser", data);
                //TODO 1、默认发的令牌。session=dssadd。作用域:当前域；(解决子域session共享问题)
                //TODO 2、使用json的序列号方式来序列号对象数据到redis中
//                new Cookie("JSESSIONID", "dadad").setComment();
//                servletResponse.addCookie();


                return "redirect:http://gulimall.com";
            } else {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        } else {
            return "redirect:http://auth.gulimall.com/login.html";
        }

    }

}
